from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.views import APIView
import random
from django_redis import get_redis_connection
from meiduo.libs.yuntongxun.sms import CCP
from rest_framework.response import Response
from celery_tasks.sms.tasks import send_sms_code


class SMSCodeView(APIView):
    """短信验证码"""
    def get(self, request, mobile):
        sms_code = '%06d' % random.randint(0, 999999)
        redis_conn = get_redis_connection('verify_codes')
        result = redis_conn.get('sms_has_%s' % mobile)
        if result:
            return Response({'message': '不能频繁发送短信'}, status=status.HTTP_400_BAD_REQUEST)

        redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        redis_conn.setex('sms_has_%s' % mobile, 60, 1)

        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # 触发异步任务
        send_sms_code.delay(mobile, sms_code)

        return Response({"message": "OK"})



